﻿#include "train_admin.h"
#include "Global_Class.h"
#include "AllData.h"
#include "ui_train_admin.h"
#include "orders.h"
#include "TrainAdminDialog.h"
#include "ScheduleAdminDialog.h"
#include <QDateTime>
#include <QMessageBox>


// 辅助函数：将时间字符串转换为分钟数
int timeStringToMinutes(const std::string& timeStr) {
    if (timeStr.length() < 5) return -1; // 无效时间

    try {
        int hours = std::stoi(timeStr.substr(0, 2));
        int minutes = std::stoi(timeStr.substr(3, 2));
        return hours * 60 + minutes;
    }
    catch (...) {
        return -1; // 转换失败
    }
}

QString calculateDuration(const std::string& arrival, const std::string& depart) {
    int arrivalMin = timeStringToMinutes(arrival);
    int departMin = timeStringToMinutes(depart);

    if (arrivalMin < 0 || departMin < 0) return "-";

    // 处理跨天（次日到达）
    if (departMin < arrivalMin) {
        departMin += 24 * 60;
    }

    int durationMin = departMin - arrivalMin;
    if (durationMin <= 0) return "-";

    int hours = durationMin / 60;
    int minutes = durationMin % 60;

    if (hours > 0) {
        return QString("%1小时%2分").arg(hours).arg(minutes);
    }
    return QString("%1分").arg(minutes);
}

//train_admin::train_admin(QWidget* parent)
//    : QMainWindow(parent)
//{
//    ui.setupUi(this);
//    connect(ui.refreshButton, &QPushButton::clicked, this, &train_admin::refreshTUTable);
//    connect(ui.trainInfoAdminBtn, &QPushButton::clicked, this, &train_admin::onTrainInfoManagementAction);
//    refreshTUTable();
//}

train_admin::~train_admin()
{
}

//void train_admin::refreshTUTable()
//{
//    QTableWidget* table = ui.tableWidget;
//    table->clear();
//    table->setRowCount(0);
//    table->setColumnCount(8); // 8列：列车+站点信息+3种余票
//
//    // 设置表头
//    QStringList headers;
//    headers << "列车名称"
//        << "途经站点"
//        << "到站时间"
//        << "出站时间"
//        << "停靠时长"
//        << "此时剩余商务票票数"
//        << "此时剩余一等票票数"
//        << "此时剩余二等票票数";
//    table->setHorizontalHeaderLabels(headers);
//
//    // 获取用户选择的时间
//    QDateTime selectedDateTime = ui.dateTimeEdit->dateTime();
//    QDate selectedDate = selectedDateTime.date();
//    std::string selectedDateStr = selectedDate.toString("yyyy-MM-dd").toStdString();
//
//    // 按列车ID分组时刻表
//    //std::map<int, std::vector<train_schedule>> tSchedules;
//    //for (auto& schedule : allData->trainSchedules) {
//    //    tSchedules[schedule.getTrainId()].push_back(schedule);
//    //}
//    std::map<int, std::vector<train_schedule>> tSchedules;
//    for (auto& schedule : allData->trainSchedules) {
//        tSchedules[schedule.getTrainId()].push_back(schedule);
//    }
//
//    // 按列车ID排序
//    std::vector<int> trainIds;
//    for (auto& pair : tSchedules) {
//        trainIds.push_back(pair.first);
//    }
//    //std::sort(trainIds.begin(), trainIds.end());
//
//    // 创建座位类型映射 (seat_id -> seat_type) 提高效率
//    std::unordered_map<int, std::string> seatTypeMap;
//    for (auto& seat : allData->seatsQueue) {
//        seatTypeMap[seat.getSeatId()] = seat.getSeatType();
//    }
//
//
//
//
//    // 填充表格
//    for (int trainId : trainIds) {
//        auto& schedules = tSchedules[trainId];
//        //std::sort(schedules.begin(), schedules.end(),
//        //    [](train_schedule& a, train_schedule& b) {
//        //        return a.getStopOrder() < b.getStopOrder();
//        //    });
//
//        // 获取列车名称
//        QString trainName = "未知列车";
//        for (auto& train : allData->trainQueue) {
//            if (train.getTrainId() == trainId) {
//                trainName = QString::fromStdString(train.getTrainCode());
//                break;
//            }
//        }
//		if (trainName == "未知列车")//解决一个小bug：如果没有找到列车信息，则跳过该列车
//        {
//            continue;
//        }
//
//        // 计算该列车各座位类型总座位数
//        int totalBusiness = 0, totalFirst = 0, totalSecond = 0;
//        for (auto& seat : allData->seatsQueue) {
//            if (seat.getTrainId() == trainId) {
//                QString type = QString::fromStdString(seat.getSeatType()).trimmed();
//                if (type == "商务座") totalBusiness++;
//                else if (type == "一等座") totalFirst++;
//                else if (type == "二等座") totalSecond++;
//            }
//        }
//
//        // 创建站点ID到停靠顺序的映射
//        std::map<int, int> stationOrderMap;
//        for (auto& schedule : schedules) {
//            stationOrderMap[schedule.getStationId()] = schedule.getStopOrder();
//        }
//
//        // 初始化每个站点的占用计数
//        std::map<int, std::tuple<int, int, int>> stationOccupancy;
//        for (auto& schedule : schedules) {
//            stationOccupancy[schedule.getStationId()] = { 0, 0, 0 };
//        }
//
//        // 处理有效订单（booked状态且日期匹配）
//        for (auto& order : allData->ordersQueue) {
//            if (order.getTrainId() == trainId 
//                &&
//                order.getStatus() == orders::OrderStatus::booked
//                &&
//                order.getTravelDate() == selectedDateStr
//                )
//            {
//                int startOrder = stationOrderMap[order.getStartStationId()];
//                int endOrder = stationOrderMap[order.getEndStationId()];
//                
//                // 直接从映射获取座位类型
//                std::string seatType = seatTypeMap[order.getSeatId()];
//                QString qSeatType = QString::fromStdString(seatType).trimmed();
//
//                // 更新受影响的站点占用
//                for (auto& schedule : schedules) {
//                    int stationOrder = schedule.getStopOrder();
//                    if (stationOrder >= startOrder && stationOrder <= endOrder) {
//                        auto& [bus, fir, sec] = stationOccupancy[schedule.getStationId()];
//                        if (qSeatType == "商务座") bus++;
//                        else if (qSeatType == "一等座") fir++;
//                        else if (qSeatType == "二等座") sec++;
//                    }
//                }
//            }
//        }
//        bool isFirstRow = true;
//        int prevBusinessTicket = -1, prevFirstTicket = -1, prevSecondTicket = -1;
//
//        for (size_t i = 0; i < schedules.size(); i++) {
//            auto& schedule = schedules[i];
//            int row = table->rowCount();
//            table->insertRow(row);
//
//            // 列车名称列（只在第一行显示）
//            if (isFirstRow) {
//                table->setItem(row, 0, new QTableWidgetItem(trainName));
//                isFirstRow = false;
//            }
//            else {
//                table->setItem(row, 0, new QTableWidgetItem(""));
//            }
//
//            // 站点名称
//            QString stationName = "未知站点";
//            for (auto& station : allData->stationsQueue) {
//                if (station.getStationId() == schedule.getStationId()) {
//                    stationName = QString::fromStdString(station.getName());
//                    break;
//                }
//            }
//
//            // 时间信息
//            QString arrival = QString::fromStdString(schedule.getArrivalTime());
//            QString depart = QString::fromStdString(schedule.getDepartTime());
//            QString duration = calculateDuration(schedule.getArrivalTime(), schedule.getDepartTime());
//
//            // 填充基础信息
//            table->setItem(row, 1, new QTableWidgetItem(stationName));
//            table->setItem(row, 2, new QTableWidgetItem(arrival));
//            table->setItem(row, 3, new QTableWidgetItem(depart));
//            table->setItem(row, 4, new QTableWidgetItem(duration));
//
//            // 计算当前站点的余票
//            auto [busOccupancy, firOccupancy, secOccupancy] = stationOccupancy[schedule.getStationId()];
//            int businessTicket = totalBusiness - busOccupancy;
//            int firstTicket = totalFirst - firOccupancy;
//            int secondTicket = totalSecond - secOccupancy;
//
//            // 确保余票不为负
//            businessTicket = std::max(0, businessTicket);
//            firstTicket = std::max(0, firstTicket);
//            secondTicket = std::max(0, secondTicket);
//            //// 终点站特殊处理（余票为0）
//            //if (i == schedules.size() - 1) {
//            //    businessTicket = 0;
//            //    firstTicket = 0;
//            //    secondTicket = 0;
//            //}
//
//            //// 更新前一个站点的余票记录
//            //prevBusinessTicket = businessTicket;
//            //prevFirstTicket = firstTicket;
//            //prevSecondTicket = secondTicket;
//
//            // 设置余票数据
//            table->setItem(row, 5, new QTableWidgetItem(QString::number(businessTicket)));
//            table->setItem(row, 6, new QTableWidgetItem(QString::number(firstTicket)));
//            table->setItem(row, 7, new QTableWidgetItem(QString::number(secondTicket)));
//        }
//    }
//
//    // 合并相同列车的名称单元格
//    int startRow = -1;
//    int mergeCount = 0;
//    QString currentTrain;
//    int totalRows = table->rowCount();
//
//    for (int row = 0; row < totalRows; row++) {
//        QTableWidgetItem* item = table->item(row, 0);
//        QString trainName = item ? item->text() : "";
//
//        if (!trainName.isEmpty()) {
//            if (trainName != currentTrain) {
//                if (mergeCount > 1) {
//                    table->setSpan(startRow, 0, mergeCount, 1);
//                }
//                startRow = row;
//                mergeCount = 1;
//                currentTrain = trainName;
//            }
//            else {
//                mergeCount++;
//            }
//        }
//        else if (startRow >= 0) {
//            mergeCount++;
//        }
//    }
//
//    if (mergeCount > 1 && startRow >= 0) {
//        table->setSpan(startRow, 0, mergeCount, 1);
//    }
//
//    // 调整表格显示
//    table->resizeColumnsToContents();
//    table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
//}

void train_admin::SetupTUToolBar()
{
    // Implementation for setting up the toolbar for train user management
    // This function should create and configure the toolbar with necessary actions
}

void train_admin::onTrainInfoManagementAction()
{
    TrainAdminDialog* dlg = new TrainAdminDialog(this);
    dlg->exec();
    delete dlg;
}

void train_admin::onScheduleManagementAction()
{
    ScheduleAdminDialog* dlg = new ScheduleAdminDialog(this);
    dlg->exec();
    delete dlg;
}


//以下是优化UI后的版本！-------------------------------------------------------------------------

train_admin::train_admin(QWidget* parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    // 设置窗口属性
    setWindowTitle("列车时刻与余票查询系统");
    setMinimumSize(1400, 800);

    // 设置全局字体
    QFont globalFont("Microsoft YaHei", 10);
    this->setFont(globalFont);

    // 优化UI控件
    setupUI();

    connect(ui.refreshButton, &QPushButton::clicked, this, &train_admin::refreshTUTable);
    connect(ui.trainInfoAdminBtn, &QPushButton::clicked, this, &train_admin::onTrainInfoManagementAction);
    refreshTUTable();
}

void train_admin::setupUI()
{
    //// 设置主窗口背景
    //setStyleSheet(R"(
    //    QMainWindow {
    //        background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
    //                                  stop: 0 #f5f7fa, stop: 1 #e4e7ec);
    //    }
    //)");

// 优化日期时间选择器
    ui.dateTimeEdit->setDateTime(QDateTime::currentDateTime());
    ui.dateTimeEdit->setCalendarPopup(true);
    ui.dateTimeEdit->setDisplayFormat("yyyy年MM月dd日  HH:mm");
    ui.dateTimeEdit->setStyleSheet(
        "QDateTimeEdit {"
        "    padding: 8px 12px;"
        "    border: 2px solid #e0e0e0;"
        "    border-radius: 6px;"
        "    background-color: white;"
        "    color: #2c3e50;"
        "    min-height: 20px;"
        "}"
        "QDateTimeEdit:focus {"
        "    border-color: #3498db;"
        "}"
        "QDateTimeEdit::drop-down {"
        "    border: none;"
        "    width: 30px;"
        "}"
    );

    // 优化按钮样式
    auto styleButton = [](QPushButton* btn, const QString& color, const QString& hoverColor) {
        btn->setMinimumSize(100, 36);
        btn->setCursor(Qt::PointingHandCursor);
        QString style = QString(
            "QPushButton { "
            "    background-color: %1; "
            "    color: white; "
            "    border: none; "
            "    border-radius: 6px; "
            "    padding: 8px 16px; "
            "    font-weight: bold; "
            "} "
            "QPushButton:hover { "
            "    background-color: %2; "
            "} "
            "QPushButton:pressed { "
            "    background-color: %1; "
            "} "
            "QPushButton:disabled { "
            "    background-color: #bdc3c7; "
            "    color: #7f8c8d; "
            "}"
        ).arg(color, hoverColor);
        btn->setStyleSheet(style);
        };

    styleButton(ui.refreshButton, "#3498db", "#2980b9");
    styleButton(ui.trainInfoAdminBtn, "#27ae60", "#219653");

    // 添加标题标签
    QLabel* titleLabel = new QLabel("列车时刻与余票查询", this);
    titleLabel->setFont(QFont("Microsoft YaHei", 16, QFont::Bold));
    titleLabel->setStyleSheet("color: #2c3e50; padding: 15px;");
    titleLabel->setAlignment(Qt::AlignCenter);

    // 将标题添加到布局中（假设有垂直布局）
    if (ui.centralwidget->layout()) {
        // 如果已经有布局，插入标题
        QVBoxLayout* mainLayout = qobject_cast<QVBoxLayout*>(ui.centralwidget->layout());
        if (mainLayout) {
            mainLayout->insertWidget(0, titleLabel);
        }
    }

    // 设置表格样式
    ui.tableWidget->setStyleSheet(R"(
        QTableWidget {
            background-color: white;
            border: 1px solid #e1e8ed;
            border-radius: 8px;
            gridline-color: #f0f0f0;
            outline: none;
            alternate-background-color: #fafbfc;
        }
        QTableWidget::item {
            border: none;
            padding: 8px 12px;
            color: #2c3e50;
            border-bottom: 1px solid #f8f9fa;
        }
        QTableWidget::item:selected {
            background-color: #e3f2fd;
            color: #1565c0;
        }
        QTableWidget::item:hover {
            background-color: #f5f5f5;
        }
        QHeaderView::section {
            background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                      stop: 0 #34495e, stop: 1 #2c3e50);
            color: white;
            padding: 12px 8px;
            border: none;
            font-weight: bold;
            border-right: 1px solid #455a64;
            font-family: 'Microsoft YaHei';
        }
        QHeaderView::section:last {
            border-right: none;
        }
    )");
}

void train_admin::refreshTUTable()
{
    QTableWidget* table = ui.tableWidget;
    table->clear();
    table->setRowCount(0);
    table->setColumnCount(8); // 8列：列车+站点信息+3种余票

    // 设置表头
    QStringList headers;
    headers << "列车名称"
        << "途经站点"
        << "到站时间"
        << "出站时间"
        << "停靠时长"
        << "商务座余票"
        << "一等座余票"
        << "二等座余票";
    table->setHorizontalHeaderLabels(headers);

    // 设置表头字体
    QFont headerFont("Microsoft YaHei", 10, QFont::Bold);
    table->horizontalHeader()->setFont(headerFont);

    // 获取用户选择的时间
    QDateTime selectedDateTime = ui.dateTimeEdit->dateTime();
    QDate selectedDate = selectedDateTime.date();
    std::string selectedDateStr = selectedDate.toString("yyyy-MM-dd").toStdString();

    // 显示加载状态
    QApplication::setOverrideCursor(Qt::WaitCursor);

    // 按列车ID分组时刻表
    std::map<int, std::vector<train_schedule>> tSchedules;
    for (auto& schedule : allData->trainSchedules) {
        tSchedules[schedule.getTrainId()].push_back(schedule);
    }

    // 按列车ID排序
    std::vector<int> trainIds;
    for (auto& pair : tSchedules) {
        trainIds.push_back(pair.first);
    }

    // 创建座位类型映射 (seat_id -> seat_type) 提高效率
    std::unordered_map<int, std::string> seatTypeMap;
    for (auto& seat : allData->seatsQueue) {
        seatTypeMap[seat.getSeatId()] = seat.getSeatType();
    }

    // 填充表格
    int totalRecords = 0;
    for (int trainId : trainIds) {
        auto& schedules = tSchedules[trainId];

        // 获取列车名称
        QString trainName = "未知列车";
        for (auto& train : allData->trainQueue) {
            if (train.getTrainId() == trainId) {
                trainName = QString::fromStdString(train.getTrainCode());
                break;
            }
        }
        if (trainName == "未知列车") {
            continue;
        }

        // 计算该列车各座位类型总座位数
        int totalBusiness = 0, totalFirst = 0, totalSecond = 0;
        for (auto& seat : allData->seatsQueue) {
            if (seat.getTrainId() == trainId) {
                QString type = QString::fromStdString(seat.getSeatType()).trimmed();
                if (type == "商务座") totalBusiness++;
                else if (type == "一等座") totalFirst++;
                else if (type == "二等座") totalSecond++;
            }
        }

        // 创建站点ID到停靠顺序的映射
        std::map<int, int> stationOrderMap;
        for (auto& schedule : schedules) {
            stationOrderMap[schedule.getStationId()] = schedule.getStopOrder();
        }

        // 初始化每个站点的占用计数
        std::map<int, std::tuple<int, int, int>> stationOccupancy;
        for (auto& schedule : schedules) {
            stationOccupancy[schedule.getStationId()] = { 0, 0, 0 };
        }

        // 处理有效订单（booked状态且日期匹配）
        for (auto& order : allData->ordersQueue) {
            if (order.getTrainId() == trainId
                && order.getStatus() == orders::OrderStatus::booked
                && order.getTravelDate() == selectedDateStr) {

                int startOrder = stationOrderMap[order.getStartStationId()];
                int endOrder = stationOrderMap[order.getEndStationId()];

                // 直接从映射获取座位类型
                std::string seatType = seatTypeMap[order.getSeatId()];
                QString qSeatType = QString::fromStdString(seatType).trimmed();

                // 更新受影响的站点占用
                for (auto& schedule : schedules) {
                    int stationOrder = schedule.getStopOrder();
                    if (stationOrder >= startOrder && stationOrder <= endOrder) {
                        auto& [bus, fir, sec] = stationOccupancy[schedule.getStationId()];
                        if (qSeatType == "商务座") bus++;
                        else if (qSeatType == "一等座") fir++;
                        else if (qSeatType == "二等座") sec++;
                    }
                }
            }
        }

        bool isFirstRow = true;
        for (size_t i = 0; i < schedules.size(); i++) {
            auto& schedule = schedules[i];
            int row = table->rowCount();
            table->insertRow(row);
            totalRecords++;

            table->setRowHeight(row, 40); // 将行高设置为40像素

            // 列车名称列（只在第一行显示）
            if (isFirstRow) {
                QTableWidgetItem* trainItem = new QTableWidgetItem(trainName);
                trainItem->setFont(QFont("Microsoft YaHei", 10, QFont::Bold));
                // 设置文本自动换行，确保长名称也能显示
                trainItem->setTextAlignment(Qt::AlignLeft | Qt::AlignVCenter);
                table->setItem(row, 0, trainItem);
                isFirstRow = false;
            }
            else {
                table->setItem(row, 0, new QTableWidgetItem(""));
            }

            // 站点名称
            QString stationName = "未知站点";
            for (auto& station : allData->stationsQueue) {
                if (station.getStationId() == schedule.getStationId()) {
                    stationName = QString::fromStdString(station.getName());
                    break;
                }
            }

            // 时间信息
            QString arrival = QString::fromStdString(schedule.getArrivalTime());
            QString depart = QString::fromStdString(schedule.getDepartTime());
            QString duration = calculateDuration(schedule.getArrivalTime(), schedule.getDepartTime());

            // 填充基础信息
            table->setItem(row, 1, new QTableWidgetItem(stationName));
            table->setItem(row, 2, new QTableWidgetItem(arrival));
            table->setItem(row, 3, new QTableWidgetItem(depart));
            table->setItem(row, 4, new QTableWidgetItem(duration));

            // 计算当前站点的余票
            auto [busOccupancy, firOccupancy, secOccupancy] = stationOccupancy[schedule.getStationId()];
            int businessTicket = totalBusiness - busOccupancy;
            int firstTicket = totalFirst - firOccupancy;
            int secondTicket = totalSecond - secOccupancy;

            // 确保余票不为负
            businessTicket = std::max(0, businessTicket);
            firstTicket = std::max(0, firstTicket);
            secondTicket = std::max(0, secondTicket);

            // 设置余票数据，根据余票数量设置颜色
            auto createTicketItem = [](int ticketCount, int total) {
                QTableWidgetItem* item = new QTableWidgetItem(QString::number(ticketCount));
                // 根据余票比例设置颜色
                if (ticketCount == 0) {
                    item->setForeground(QColor("#e74c3c")); // 红色，无票
                    item->setToolTip("无票");
                }
                else if (ticketCount < total * 0.3) {
                    item->setForeground(QColor("#e67e22")); // 橙色，票量紧张
                    item->setToolTip("票量紧张");
                }
                else {
                    item->setForeground(QColor("#27ae60")); // 绿色，票量充足
                    item->setToolTip("票量充足");
                }
                item->setTextAlignment(Qt::AlignCenter);
                return item;
                };

            table->setItem(row, 5, createTicketItem(businessTicket, totalBusiness));
            table->setItem(row, 6, createTicketItem(firstTicket, totalFirst));
            table->setItem(row, 7, createTicketItem(secondTicket, totalSecond));
        }
    }

    // 合并相同列车的名称单元格
    int startRow = -1;
    int mergeCount = 0;
    QString currentTrain;
    int totalRows = table->rowCount();

    for (int row = 0; row < totalRows; row++) {
        QTableWidgetItem* item = table->item(row, 0);
        QString trainName = item ? item->text() : "";

        if (!trainName.isEmpty()) {
            if (trainName != currentTrain) {
                if (mergeCount > 1) {
                    table->setSpan(startRow, 0, mergeCount, 1);
                }
                startRow = row;
                mergeCount = 1;
                currentTrain = trainName;
            }
            else {
                mergeCount++;
            }
        }
        else if (startRow >= 0) {
            mergeCount++;
        }
    }

    if (mergeCount > 1 && startRow >= 0) {
        table->setSpan(startRow, 0, mergeCount, 1);
    }
    // 调整表格显示 - 重点增加最左列宽度
    table->resizeColumnsToContents();

    // 设置合理的列宽 - 大幅增加最左列宽度
    table->setColumnWidth(0, 200); // 列车名称 - 从150增加到200，确保长名称完整显示
    table->setColumnWidth(1, 180); // 途经站点 - 稍微增加以平衡布局
    table->setColumnWidth(2, 100); // 到站时间
    table->setColumnWidth(3, 100); // 出站时间
    table->setColumnWidth(4, 80);  // 停靠时长
    table->setColumnWidth(5, 100); // 商务座余票
    table->setColumnWidth(6, 100); // 一等座余票
    table->setColumnWidth(7, 100); // 二等座余票

    // 根据行号位数自动调整宽度（更智能）
    int rowCount = table->rowCount();
    int digitCount = 1;
    if (rowCount > 0) {
        digitCount = QString::number(rowCount).length(); // 计算行号的最大位数
    }
    // 根据位数设置宽度，每个数字约8像素，加上边距
    int verticalHeaderWidth = qMax(40, digitCount * 8 + 20);
    table->verticalHeader()->setFixedWidth(verticalHeaderWidth);

    // 恢复光标
    QApplication::restoreOverrideCursor();

    // 显示统计信息
    QString statusInfo = QString("共加载 %1 条记录，%2 个车次").arg(totalRecords).arg(trainIds.size());
    // 如果有状态栏，可以在这里显示
    statusBar()->showMessage(statusInfo, 5000);
}